package com.iskny.framework.kit;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;

import java.util.List;

/**
 * 
 * @author 伟强
 *
 */
@SuppressWarnings("rawtypes")
public class ModelKit {
	private final Model dao;
    private final String cacheNameForOneModel;
    private final String cloumns;
    public ModelKit(Model dao, String cacheNameForOneModel,String cloumns){
        this.dao = dao;
        this.cacheNameForOneModel = cacheNameForOneModel;
        boolean isall = false;
        if(cloumns==null||cloumns.equals("")){
        	cloumns = "*";
        	isall = true;
        }
        this.cloumns = cloumns;
        if(!isall){//except undefined cloumns
        	 for(String item:cloumns.split(",")){
     			dao.set(item,null);
     		}
        }
    }
    public <M> Page<M> loadModelPage(Page<M> page) {
        List<M> modelList = page.getList();
        for(int i = 0; i < modelList.size(); i++){
            Model model = (Model)modelList.get(i);
            M topic = loadModel(model.getInt("id"));
            modelList.set(i, topic);
        }
        return page;
    }
    public <M> M loadModel(int id) {
        final int ID = id;
        return CacheKit.get(cacheNameForOneModel, ID, new IDataLoader() {
            @Override
            public Object load() {
                return dao.findById(ID,cloumns);
            }
        });
    }
}
